<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>商品购物车</title>
    <link rel="shortcut icon" href="./../../favicon.ico">
    <link rel="stylesheet" href="../../style/cart/shoppingCart.css">
    <script type="text/javascript" src="./../../plugins/jQuery/jquery-3.6.0.js"></script>
    <script type="text/javascript" src="./../../plugins/vue/vue.js"></script>
    <script type="text/javascript" src="./../../plugins/axios/axios.js"></script>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="./../../plugins/element-ui/index.css">
    <!-- 引入组件库 -->
    <script src="./../../plugins/element-ui/index.js"></script>
    <!-- 引入layer -->
    <script src="../../plugins/layer-master/dist/layer.js"></script>
    <style>
        .el-table {
            margin: 0 auto;
        }
    </style>
</head>
<body>
<div id="app">
    <nav class="public-header">
        <a href="../../index.html">网站首页</a>
        <a href="">我的订单</a>
        <a href="">我的地址</a>
    </nav>
    <div class="cart">
        <template>
            <el-table
                    ref="multipleTable"
                    :data="cartItems"
                    tooltip-effect="dark"
                    style="width: 87%"
                    @selection-change="selectedCheckbox"
            >
                <el-table-column
                        type="selection"
                        width="55"
                        align="center"
                >
                </el-table-column>
                <el-table-column
                        label="商品"
                        width="220"
                        align="center"
                >
                    <template slot-scope="scope">
                        <img width="120px" :src=`http:${scope.row.imageName}`>
                    </template>
                </el-table-column>
                <el-table-column
                        label="书名"
                        align="center"
                >
                    <template slot-scope="scope">
                        {{scope.row.name}}
                    </template>
                </el-table-column>
                <el-table-column
                        label="出版社"
                        align="center"
                >
                    <template slot-scope="scope">
                        {{scope.row.publisher}}
                    </template>
                </el-table-column>
                <el-table-column
                        prop="price"
                        label="单价"
                        width="120"
                        align="center"
                >
                    <template slot-scope="scope">￥{{ scope.row.price }}元</template>
                </el-table-column>
                <el-table-column
                        prop="number"
                        label="数量"
                        show-overflow-tooltip
                        align="center"
                        width="200px"
                >
                    <template slot-scope="scope">
                        <el-button size="mini" type="danger" @click="changeNumber1(scope.row.bookId,-1)">-1</el-button>
                        <input type="text"
                               style="width: 50px; height: 23px"
                               v-model.number="scope.row.number"
                               @click="getOldNumber(scope.row.number)"
                               @change="changeNumber2(scope.row)"
                        >
                        <el-button size="mini" type="success" @click="changeNumber1(scope.row.bookId,1)">+1</el-button>
                    </template>

                </el-table-column>
                <el-table-column
                        prop="address"
                        label="小计"
                        show-overflow-tooltip
                        align="center"
                        width="120"
                >
                    <template slot-scope="scope">
                        <span v-if='scope.row.chongzu'>
                               库存不足
                        </span>
                        <span v-else>
                            ￥{{ (scope.row.price * scope.row.number).toFixed(2) }}元
                        </span>


                    </template>
                </el-table-column>
                <el-table-column
                        prop="address"
                        label="操作"
                        show-overflow-tooltip
                        align="center"
                        width="120"
                >
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                type="danger"
                                align="center"
                                @click="removeGwc(scope.row)"
                        >删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-button type="danger" class="dangers" v-if="cartItems.length > 0" id="batchDeleteBtn"
                       @click="removeBatchGwc"
            >批量删除
            </el-button>
            <div class="cart-btn"><span>总价：</span><span> ¥{{totalPrice}} </span>
                <button class="btn" @click="toPay">去结算</button>
            </div>
        </template>
        <!-- 页脚部分 -->
        <div class="extra">
            <div class="wrapper">
                <!-- 版权信息 -->
                <div class="copyright">
                    <p>
                        <a href="javascript:;">关于我们</a>
                        <a href="javascript:;">帮助中心</a>
                        <a href="javascript:;">售后服务</a>
                        <a href="javascript:;">配送与验收</a>
                        <a href="javascript:;">商务合作</a>
                        <a href="javascript:;">搜索推荐</a>
                        <a href="javascript:;">友情链接</a>
                    </p>
                    <p>CopyRight &copy; 加中实训</p>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    const vm = new Vue({
        el: "#app",
        data: {
            userId: "",
            // 购物车列表
            cartItems: [],
            // 选中了的购物项列表
            selectedItemList: [],
            // 库存集合
            stockItems: [],
            oldNumber: 0
        },
        methods: {
            // 加载我的购物车
            loadGwcData() {
                axios({
                    method: 'get',
                    url: 'http://localhost:9000/shopping/find',
                    headers: {
                        token: localStorage.getItem('bookstore_front_token')
                    }
                }).then(resp => {
                    if (resp.data.success) {
                        this.cartItems = resp.data.data
                    } else {
                        this.$message({
                            type: 'error',
                            message: resp.data.error,
                            duration: 3000,
                            onClose: function () {
                                location.href = '../login/login.html'
                            }
                        });
                    }
                })
            },
            selectedCheckbox(selection) {
                this.selectedItemList = selection
                // 判断图书库存是否充足
                for (let i = 0; i < this.cartItems.length; i++) {
                    let book = this.cartItems[i]
                    console.log(book)
                    for (let j = 0; j < this.stockItems.length; j++) {
                        let stock = this.stockItems[j]
                        if (book.bookId === stock.bookId) {
                            if (book.number <= stock.number) {
                                book.chongzu = false
                            } else {
                                book.chongzu = true
                            }
                            console.log(book.bookId + '库存数量' + (book.chongzu ? "充足" : "不充足"))
                            break
                        }
                    }
                }
            },
            // 加载我购物车信息的库存
            loadStockData() {
                axios({
                    method: 'get',
                    url: 'http://localhost:9000/stock/find',
                    headers: {
                        token: localStorage.getItem('bookstore_front_token')
                    }
                }).then(resp => {
                    this.stockItems = resp.data.data
                })
            },
            // 修改数量
            changeNumber1(bookId, number) {
                axios({
                    method: 'put',
                    url: 'http://localhost:9000/shopping/change_number/' + bookId + '/' + number,
                    headers: {
                        token: localStorage.getItem('bookstore_front_token')
                    }
                }).then(resp => {
                    if (resp.data.success) {
                        this.loadGwcData()
                    } else {
                        this.$message({
                            type: 'error',
                            message: resp.data.error
                        });
                    }
                })
            },
            changeNumber2(row) {
                console.log(this.oldNumber)
                let zhengze = /^\d+$/
                let flag = zhengze.test(row.number)
                if (!flag) {
                    row.number = this.oldNumber
                    this.$message({
                        type: 'error',
                        message: '请输入一个数字'
                    });
                    return
                }
                axios({
                    method: 'put',
                    url: 'http://localhost:9000/shopping/change_number2/' + row.bookId + '/' + row.number,
                    headers: {
                        token: localStorage.getItem('bookstore_front_token')
                    }
                }).then(resp => {
                    console.log(1212121)
                    if (resp.data.success) {
                        this.$message({
                            type: 'success',
                            message: '数量修改成功'
                        });
                        this.loadGwcData()
                    } else {
                        row.number = this.oldNumber
                        this.$message({
                            type: 'error',
                            message: resp.data.error
                        });
                    }
                    console.log('1111111')
                    console.log(row)
                })

            },
            getOldNumber(number) {
                this.oldNumber = number
                console.log(this.oldNumber + ".....")
            },
            // 删除选中图书
            removeGwc(row) {
                this.$confirm('此操作将移除该图书, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 点击确定后执行的操作
                    axios({
                        method: 'delete',
                        url: 'http://localhost:9000/shopping/remove/' + row.bookId,
                        headers: {
                            token: localStorage.getItem('bookstore_front_token')
                        }
                    }).then(resp => {
                        if (resp.data.success) {
                            this.$message({
                                type: 'success',
                                message: '移除成功'
                            });
                            this.loadGwcData()
                        }
                    })

                }).catch(() => {
                    // 点击取消后执行的操作
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            removeBatchGwc() {
                let bookId = ''
                for (let i = 0; i < this.selectedItemList.length; i++) {
                    bookId += this.selectedItemList[i].bookId + 'A'
                }
                this.$confirm('此操作将移除选中图书, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 点击确定后执行的操作
                    axios({
                        method: 'delete',
                        url: 'http://localhost:9000/shopping/remove_batch',
                        headers: {
                            token: localStorage.getItem('bookstore_front_token')
                        },
                        params: {
                            bookId: bookId
                        }
                    }).then(resp => {
                        if (resp.data.success) {
                            this.$message({
                                type: 'success',
                                message: '移除成功'
                            });
                            this.loadGwcData()
                        }
                    })

                }).catch(() => {
                    // 点击取消后执行的操作
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            toPay() {
                let obj = {}
                obj.totalAmount = this.totalPrice
                obj.status = '5'
                obj.totalCount = 0
                obj.orderItems = []
                let list = this.selectedItemList
                for (let i = 0; i < list.length; i++) {
                    let e = list[i]
                    obj.totalCount += e.number
                    let orderItem = {}
                    orderItem.bookId = e.bookId
                    orderItem.number = e.number
                    obj.orderItems[i] = orderItem
                }
                axios({
                    method: 'post',
                    url: 'http://localhost:9000/order',
                    data: obj,
                    headers: {
                        token: localStorage.getItem('bookstore_front_token')
                    }
                }).then(resp => {
                    sessionStorage.setItem("TOTAL_AMOUNT",this.totalPrice)
                    sessionStorage.setItem("ORDER_ID", resp.data.data)
                    sessionStorage.setItem('ORDER_THIS', JSON.stringify(this.selectedItemList))
                    location.href = '../order/order.html'
                })

            }
        },
        computed: {
            // 总价格
            totalPrice() {
                return this.selectedItemList.reduce((sum, item) => {
                    sum = parseFloat(sum);
                    let price = parseFloat(item.price);
                    let number = parseFloat(item.number);
                    sum += (price * number);
                    return sum.toFixed(2);
                }, 0);
            },
        },
        created() {
            this.loadGwcData()
            this.loadStockData()
        }
    })
</script>
</body>
</html>
